package com.example.cloud.filter;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;

import lombok.extern.slf4j.Slf4j;

/**
 * 请求过滤器
 *
 * @author tongyufu
 */
@Slf4j
@Component
public class AccessFilter extends ZuulFilter {

    /**
     * 返回true时run()方法才会被执行
     */
    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
     * 举起过滤方法
     *
     * @return null
     */
    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        log.info("发送{}请求到{}", request.getMethod(), request.getRequestURL().toString());
        String accessToken = request.getParameter("accessToken");

        if (StringUtils.isBlank(accessToken)) {
            log.warn("==access token is empty");
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(401);
            ctx.setResponseBody("access token is empty");
        }
        return null;
    }

    /**
     * 过滤类型
     *
     * @return pre
     */
    @Override
    public String filterType() {
        return "pre";
    }

    /**
     * {@inheritDoc}<br>
     * 过滤器的执行顺序。当一个请求阶段中有多个过滤器时，根据返回值来依次执行。
     *
     * @return 0
     */
    @Override
    public int filterOrder() {
        return 0;
    }

}
